#!/usr/bin/env python

# copyright 2010 Studio Cypher, LLC
# developer: Will Emigh
# projects@studiocypher.com

# Custom modules
from authentication import user_required
from authentication import get_account_from_user
from models import Account
from models import Planet
from models import Colony
from models import ResourcePackage
from models import Log
from models import UnitType
from models import ColonyShip
from models import RecyclingShip
from models import FreighterShip
from models import MegaFreighterShip
from models import MOPPShip
from models import BuildingType
from models import BuildingUnit
from models import OutPost


# Built-in or Google modules
import cgi
import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users


from google.appengine.ext import db

        
class ViewPage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        #if a building has been built for use in the research tree
        #on if the next building can be made available
        colonized = False
        starportb = False
        advstarportb = False
        factoryb = False
        advfactoryb = False
        #ship costs
        colshipcost = 'n/a'
        recshipcost = 'n/a'
        freshipcost = 'n/a'
        megafreshipcost = 'n/a'
        moppshipcost = 'n/a'
        #building costs
        starportcost = 'n/a'
        smallHUcost = 'n/a'
        factorycost = 'n/a'
        advstarportcost = 'n/a'
        advfactorycost = 'n/a'
        smeucost = 'n/a'
        mediumHUcost = 'n/a'
        autoPLcost = 'n/a'
        largeHUcost = 'n/a'
        nanoassemblyost = 'n/a'
        dcmeucost = 'n/a'

        # If they don't already have an account, redirect to main
        account = get_account_from_user(user)
        if (account == None):
            self.redirect("/")
            return
        
        planet = account.current_planet
        allfreighters = FreighterShip.all()
        freighters = allfreighters.filter('owner =',account).filter('planet =',planet)

        starport_cnt = 0
        factory_cnt = 0
        advfactory_cnt = 0
        advstarport_cnt = 0
        shouse_cnt = 0
        smeu_cnt = 0
        mhouse_cnt = 0
        autoprodline_cnt = 0
        lhouse_cnt = 0
        nanassembly_cnt = 0
        dcmeu_cnt = 0
        allbuildings = BuildingUnit.all()
        userbuildings = allbuildings.filter('owner =',account).filter('planet =', planet)
        for userbuilding in userbuildings:
            if (userbuilding.type.name == 'Starport'):
                starportb = True
                starport_cnt += 1
            elif (userbuilding.type.name == 'Factory'):
                factoryb = True
                factory_cnt += 1
            elif (userbuilding.type.name == 'Advanced Factory'):
                advfactoryb = True
                advfactory_cnt += 1
            elif (userbuilding.type.name == 'Advanced Starport'):
                advstarportb = True
                advstarport_cnt += 1
            elif (userbuilding.type.name == 'Small Housing Unit'):
                shouse_cnt += 1
            elif (userbuilding.type.name == 'Supercooled Magnetic Extractor Upgrade'):
                smeu_cnt += 1
            elif (userbuilding.type.name == 'Medium Housing Unit'):
                mhouse_cnt += 1
            elif (userbuilding.type.name == 'Automated Production Lines'):
                autoprodline_cnt += 1
            elif (userbuilding.type.name == 'Large Housing Unit'):
                lhouse_cnt += 1
            elif (userbuilding.type.name == 'Nanorobotics Assembly'):
                nanassembly_cnt += 1
            elif (userbuilding.type.name == 'Deep Core Mining Extractor Upgrade'):
                dcmeu_cnt += 1

        
        colony = None
        colonies = []
        for colony_key in planet.colonies:
            tmp_colony = Colony.get(colony_key)
            colonies.append(tmp_colony)
            if tmp_colony.owner.key() == account.key():
                colonized = True
                colony = tmp_colony
        account_resources = None
        if (colonized):
            account_resources = colony.resourceStorage

        colony_ships = None
        recycler_ships = None
        freighter_ships = None
        mopp_ships = None
        megafreighter_ships = None
        all_ships = ColonyShip.all()
        colony_ships = all_ships.filter('owner =',account).filter('planet =', account.current_planet)
        all_ships = RecyclingShip.all()
        recycler_ships = all_ships.filter('owner =',account).filter('planet =', account.current_planet)
        all_ships = FreighterShip.all()
        freighter_ships = all_ships.filter('owner =',account).filter('planet =', account.current_planet)
        all_ships = MegaFreighterShip.all()
        megafreighter_ships = all_ships.filter('owner =',account).filter('planet =', account.current_planet)
        all_ships = MOPPShip.all()
        mopp_ships = all_ships.filter('owner =',account).filter('planet =', account.current_planet)
        
        colony_cnt = colony_ships.count()
        recycler_cnt = recycler_ships.count()
        freighter_cnt = freighter_ships.count()
        mopp_cnt = mopp_ships.count()
        megafre_cnt = megafreighter_ships.count()
        
        error_msg = []
        types = UnitType.all()
        for type in types:
            if (type.type == 'ColonyS'):
                colshipcost = '<br /> Minerals: ' + str(type.price.resourceOne) + '<br /> Water: ' + str(type.price.resourceTwo) + '<br /> Fuel: ' + str(type.price.resourceThree) + '<br /> Organic: ' + str(type.price.resourceFour) + '<br /> Population: ' + str(type.population)
            elif (type.type == 'RecyclingS'):
                recshipcost = '<br /> Minerals: ' + str(type.price.resourceOne) + '<br /> Water: ' + str(type.price.resourceTwo) + '<br /> Fuel: ' + str(type.price.resourceThree) + '<br /> Organic: ' + str(type.price.resourceFour) + '<br /> Population: ' + str(type.population)
            elif (type.type == 'FreighterS'):
                freshipcost = '<br /> Minerals: ' + str(type.price.resourceOne) + '<br /> Water: ' + str(type.price.resourceTwo) + '<br /> Fuel: ' + str(type.price.resourceThree) + '<br /> Organic: ' + str(type.price.resourceFour) + '<br /> Population: ' + str(type.population)
            elif (type.type == 'MegaFreighterS'):
                megafreshipcost = '<br /> Minerals: ' + str(type.price.resourceOne) + '<br /> Water: ' + str(type.price.resourceTwo) + '<br /> Fuel: ' + str(type.price.resourceThree) + '<br /> Organic: ' + str(type.price.resourceFour) + '<br /> Population: ' + str(type.population)
            elif (type.type == 'MOPPS'):
                moppshipcost = '<br /> Minerals: ' + str(type.price.resourceOne) + '<br /> Water: ' + str(type.price.resourceTwo) + '<br /> Fuel: ' + str(type.price.resourceThree) + '<br /> Organic: ' + str(type.price.resourceFour) + '<br /> Population: ' + str(type.population)
            
        buildings = BuildingType.all()
        for building in buildings:
            if (building.name == 'Starport'):
                starportcost = '<br /> Minerals: ' + str(building.price.resourceOne) + '<br /> Water: ' + str(building.price.resourceTwo) + '<br /> Fuel: ' + str(building.price.resourceThree) + '<br /> Organic: ' + str(building.price.resourceFour) + '<br /> Population: ' + str(building.population)
            elif (building.name == 'Small Housing Unit'):
                smallHUcost = '<br /> Minerals: ' + str(building.price.resourceOne) + '<br /> Water: ' + str(building.price.resourceTwo) + '<br /> Fuel: ' + str(building.price.resourceThree) + '<br /> Organic: ' + str(building.price.resourceFour) + '<br /> Population: +' + str(building.population)
            elif (building.name == 'Factory'):
                factorycost = '<br /> Minerals: ' + str(building.price.resourceOne) + '<br /> Water: ' + str(building.price.resourceTwo) + '<br /> Fuel: ' + str(building.price.resourceThree) + '<br /> Organic: ' + str(building.price.resourceFour) + '<br /> Population: ' + str(building.population)
            elif (building.name == 'Advanced Starport'):
                advstarportcost = '<br /> Minerals: ' + str(building.price.resourceOne) + '<br /> Water: ' + str(building.price.resourceTwo) + '<br /> Fuel: ' + str(building.price.resourceThree) + '<br /> Organic: ' + str(building.price.resourceFour) + '<br /> Population: ' + str(building.population)
            elif (building.name == 'Advanced Factory'):
                advfactorycost = '<br /> Minerals: ' + str(building.price.resourceOne) + '<br /> Water: ' + str(building.price.resourceTwo) + '<br /> Fuel: ' + str(building.price.resourceThree) + '<br /> Organic: ' + str(building.price.resourceFour) + '<br /> Population: ' + str(building.population)
            elif (building.name == 'Supercooled Magnetic Extractor Upgrade'):
                smeucost = '<br /> Minerals: ' + str(building.price.resourceOne) + '<br /> Water: ' + str(building.price.resourceTwo) + '<br /> Fuel: ' + str(building.price.resourceThree) + '<br /> Organic: ' + str(building.price.resourceFour) + '<br /> Population: ' + str(building.population)
            elif (building.name == 'Medium Housing Unit'):
                mediumHUcost = '<br /> Minerals: ' + str(building.price.resourceOne) + '<br /> Water: ' + str(building.price.resourceTwo) + '<br /> Fuel: ' + str(building.price.resourceThree) + '<br /> Organic: ' + str(building.price.resourceFour) + '<br /> Population: +' + str(building.population)
            elif (building.name == 'Automated Production Lines'):
                autoPLcost = '<br /> Minerals: ' + str(building.price.resourceOne) + '<br /> Water: ' + str(building.price.resourceTwo) + '<br /> Fuel: ' + str(building.price.resourceThree) + '<br /> Organic: ' + str(building.price.resourceFour) + '<br /> Population: ' + str(building.population)
            elif (building.name == 'Large Housing Unit'):
                largeHUcost = '<br /> Minerals: ' + str(building.price.resourceOne) + '<br /> Water: ' + str(building.price.resourceTwo) + '<br /> Fuel: ' + str(building.price.resourceThree) + '<br /> Organic: ' + str(building.price.resourceFour) + '<br /> Population: +' + str(building.population)
            elif (building.name == 'Nanorobotics Assembly'):
                nanoassemblycost = '<br /> Minerals: ' + str(building.price.resourceOne) + '<br /> Water: ' + str(building.price.resourceTwo) + '<br /> Fuel: ' + str(building.price.resourceThree) + '<br /> Organic: ' + str(building.price.resourceFour) + '<br /> Population: ' + str(building.population)
            elif (building.name == 'Deep Core Mining Extractor Upgrade'):
                dcmeucost = '<br /> Minerals: ' + str(building.price.resourceOne) + '<br /> Water: ' + str(building.price.resourceTwo) + '<br /> Fuel: ' + str(building.price.resourceThree) + '<br /> Organic: ' + str(building.price.resourceFour) + '<br /> Population: ' + str(building.population)



  
        account.put()
        template_values = {'account': account,
                           'colonized': colonized,
                           'starportb': starportb,
                           'advstarportb': advstarportb,
                           'factoryb': factoryb,
                           'advfactoryb': advfactoryb,
                           'planet': planet,
                           'colonies': colonies,
                           'colony': colony,
                           'resourceStorage': account_resources,
                           'colony_cnt': colony_cnt,
                           'recycler_cnt': recycler_cnt,
                           'freighter_cnt': freighter_cnt,
                           'megafre_cnt': megafre_cnt,
                           'mopp_cnt': mopp_cnt,
                           'starport_cnt': starport_cnt,
                           'factory_cnt': factory_cnt,
                           'advfactory_cnt': advfactory_cnt,
                           'advstarport_cnt': advstarport_cnt,
                           'shouse_cnt': shouse_cnt,
                           'smeu_cnt': smeu_cnt,
                           'mhouse_cnt': mhouse_cnt,
                           'autoprodline_cnt': autoprodline_cnt,
                           'lhouse_cnt': lhouse_cnt,
                           'nanassembly_cnt': nanassembly_cnt,
                           'dcmeu_cnt': dcmeu_cnt,
                           'colshipcost': colshipcost,
                           'recshipcost': recshipcost,
                           'freshipcost': freshipcost,
                           'megafreshipcost': megafreshipcost,
                           'moppshipcost': moppshipcost,
                           'freighters': freighter_ships,
                           'megafreighters': megafreighter_ships,
                           'starportcost': starportcost,
                           'advstarportcost': advstarportcost,
                           'smeucost': smeucost,
                           'mediumHUcost': mediumHUcost,
                           'autoPLcost': autoPLcost,
                           'smallHUcost': smallHUcost,
                           'factorycost': factorycost,
                           'advfactorycost': advfactorycost,
                           'largeHUcost': largeHUcost,
                           'nanoassemblycost': nanoassemblycost,
                           'dcmeucost': dcmeucost,
                           'cost': 0,
                           'home': 0}

        path = os.path.join(os.path.dirname(__file__), 'planet.html')
        self.response.out.write(template.render(path, template_values))        

class Marketplace(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        account = get_account_from_user(user)
        planet = account.current_planet

        #check to make sure this account does already have a colony here
        has_colony = False
        for colony in planet.colonies:
            if colony == account.key():
                has_colony = True
                break
                
        template_values = {}
        if 1: #(has_colony):
            path = os.path.join(os.path.dirname(__file__), 'market.html')
            self.response.out.write(template.render(path, template_values))        
            
        #self.redirect('/planet/view/')

    def post(self):
        user = users.get_current_user()
        account = get_account_from_user(user)
        planet = account.current_planet

        #check to make sure this account does already have a colony here
        has_colony = False
        for colony in planet.colonies:
            if colony == account.key():
                has_colony = True
                break
        
        if (has_colony):
            display_market()
            
        self.redirect('/planet/view/')


class Colonize(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        account = get_account_from_user(user)
        planet = account.current_planet

        #check to make sure this account doesnt already have a colony here
        colonize = True
        for colony in planet.colonies:
            if colony == account.key():
                colonize = False
        if (colonize):
            #need to remove the colony ship from the account.
            #also only colonize if a colony ship is present.
            ships = ColonyShip.all()
            for ship in ships:
                if (ship.planet.key() == planet.key() and ship.owner.key() == account.key()):
                    planet.colonize(account)
                    account.colonies.append(planet.key())
                    ship.delete()
                    break

        account.put()
        planet.put()
        error_msg = []

        self.redirect('/planet/view/')

# Allow a player to clean the current planet
class CleanPlanet(webapp.RequestHandler):
    def post(self):
        user = users.get_current_user()
        account = get_account_from_user(user)
        planet = account.current_planet
        colony = None
        colonized = False
        for colony_key in planet.colonies:
            colony = Colony.get(colony_key)
            if colony.owner.key() == account.key():
                colonized = True
                break
            

        #if they push the clean button
        costPerUnit = 1
        cleaner = self.request.get('cleanertype')
        if (cleaner == 'mopp'):
            costPerUnit = 20
        stored = colony.resourceStorage
        ships = RecyclingShip.all()
        shipOnPlanet = False
        for ship in ships:
            if (ship.planet.key() == planet.key() and ship.owner.key() == account.key()):
                shipOnPlanet = True
                break
        if (self.request.get('cleanb')):
            amountToClean = self.request.get('spendthis')
            if (not amountToClean.isdigit()):
                self.redirect('/planet/view/')
                return
            costToClean = int(amountToClean)
            amountToClean = 2 *int(amountToClean)
            if(shipOnPlanet):
                if (stored.resourceOne < costToClean or
                    stored.resourceTwo < costToClean or
                    stored.resourceThree < costToClean or
                    stored.resourceFour < costToClean):
                    self.redirect('/planet/view/')
                    return
                stored.resourceOne -= costToClean
                stored.resourceTwo -= costToClean
                stored.resourceThree -= costToClean
                stored.resourceFour -= costToClean
                if (planet.pollution > amountToClean):
                    planet.pollution -= int(amountToClean)
                else:
                    planet.pollution = 0
                #log action
                new_log = Log.log(account.email, "cleaned this amount " + str(amountToClean), planet.name, "cost: " + str(costToClean))
                #end of log action
                account.put()
                stored.put()
                planet.put()

        self.redirect('/planet/view/')

# Allow a player to load and unload resources from a ship
class ResourceStoring(webapp.RequestHandler):
    def post(self):
        user = users.get_current_user()
        account = get_account_from_user(user)
        planet = account.current_planet

        # Require an account
        if account == None:
          self.redirect('/')
          return

        # make sure you have a colony here and also make sure you have a
        # freighter here
        colonized = False
        colony = None
        for colony_key in planet.colonies:
            tmp_colony = Colony.get(colony_key)
            if tmp_colony.owner.key() == account.key():
                colonized = True
                colony = tmp_colony
        
        ship_id = self.request.get('freighter')
        if (not ship_id):
            self.redirect('/planet/view/')
            return
            
        freightertype = self.request.get('freightertype')
        ship = None
        limit = 0
        if (freightertype == 'normal'):
            ship = FreighterShip.get(ship_id)
            limit = 1000
        elif (freightertype == 'mega'):
            ship = MegaFreighterShip.get(ship_id)
            limit = 10000

        resources = []
        if (self.request.get('loadb')):
            resources.append(str(self.request.get('Minerals')))
            resources.append(str(self.request.get('Water')))
            resources.append(str(self.request.get('Fuel')))
            resources.append(str(self.request.get('Organic')))
            # make sure all values are in fact numbers
            for resource in resources:
                if (not resource.isdigit()):
                    self.redirect('/planet/view/')
                    return
            # check to make sure the amount they want to store doesnt go over
            # that freighter types limit
            totalAmount = int(resources[0]) + int(resources[1]) + int(resources[2]) + int(resources[3]) 
            if (totalAmount > limit):
                self.redirect('/planet/view/')
                return
            # check to make sure this ship doesnt already have resources stored
            if (ship.storage.resourceOne > 0 or
                ship.storage.resourceTwo > 0 or
                ship.storage.resourceThree > 0 or
                ship.storage.resourceFour > 0):
                self.redirect('/planet/view/')
                return
            # check the account to make sure the colony has the resources to store
            if (colony.resourceStorage.resourceOne < int(resources[0]) or
                colony.resourceStorage.resourceTwo < int(resources[1]) or
                colony.resourceStorage.resourceThree < int(resources[2]) or
                colony.resourceStorage.resourceFour < int(resources[3])):
                self.redirect('/planet/view/')
                return
            # store the resources
            storage = ship.storage
            storage.resourceOne = int(resources[0])
            storage.resourceTwo = int(resources[1])
            storage.resourceThree = int(resources[2])
            storage.resourceFour = int(resources[3])
            storage.put()
            resourceStorage = colony.resourceStorage
            resourceStorage.resourceOne -= storage.resourceOne
            resourceStorage.resourceTwo -= storage.resourceTwo
            resourceStorage.resourceThree -= storage.resourceThree
            resourceStorage.resourceFour -= storage.resourceFour
            #log action
            new_log = Log.log(account.email, "uploaded resources", planet.name, 
                              "Resources after uploading Minerals: " + str(resourceStorage.resourceOne) + 
                              "Water: " + str(resourceStorage.resourceTwo) +
                              "Fuels: " + str(resourceStorage.resourceThree) +
                              "Organic: " + str(resourceStorage.resourceFour))
            #end of log action
            resourceStorage.put()
            
        if (self.request.get('unloadb')):
            resourceStorage = colony.resourceStorage
            resourceStorage.resourceOne += ship.storage.resourceOne
            resourceStorage.resourceTwo += ship.storage.resourceTwo
            resourceStorage.resourceThree += ship.storage.resourceThree
            resourceStorage.resourceFour += ship.storage.resourceFour
            resourceStorage.put()
            storage = ship.storage
            #log action
            if (storage.resourceOne > 0 or storage.resourceTwo > 0 or
                storage.resourceThree > 0 or storage.resourceFour > 0):
                new_log = Log.log(account.email, "unloaded resources", planet.name,
                                  "Resources after uploading Minerals: " + str(resourceStorage.resourceOne) +
                                  "Water: " + str(resourceStorage.resourceTwo) +
                                  "Fuels: " + str(resourceStorage.resourceThree) +
                                  "Organic: " + str(resourceStorage.resourceFour))
            #end of log action
            storage.resourceOne = 0
            storage.resourceTwo = 0
            storage.resourceThree = 0
            storage.resourceFour = 0
            storage.put()
        
        error_msg = []
        self.redirect('/planet/view/')

# Allow a player to purchase a building
class PurchaseBuilding(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        account = get_account_from_user(user)
        # Require an account
        if account == None:
          self.redirect('/')
          return

        planet = account.current_planet

        colony = None
        for colony_key in planet.colonies:
            colony = Colony.get(colony_key)
            if colony.owner.key() == account.key():
                colonized = True
                break

        error_msg = []
        buildingname = self.request.get('buildingpicked')
        #check to see if building was selected
        if (not buildingname):
            self.redirect('/planet/view/')
            return
        #check to see if the discount buildings are already made
        buildingsUnits = BuildingUnit.all()
        userbuildings = buildingsUnits.filter('owner =', account).filter('planet =', planet)
        nano = 0
        auto = 0
        for building in userbuildings:
            if (building.type.name == 'Automated Production Lines'):
                auto = 2
            elif (building.type.name == 'Nanorobotics Assembly'):
                nano = 4
        discount = nano + auto
        buildings = BuildingType.all()
        buildingtype = buildings.filter('name =', buildingname)
        buildingtype = buildingtype[0]
        #discount the price for the rest of this function
        if (buildingtype.price.resourceOne > discount):
            buildingtype.price.resourceOne = buildingtype.price.resourceOne - discount
        else:
            buildingtype.price.resourceOne = 0
        if (buildingtype.price.resourceTwo > discount):
            buildingtype.price.resourceTwo = buildingtype.price.resourceTwo - discount
        else:
            buildingtype.price.resourceTwo = 0
        if (buildingtype.price.resourceThree > discount):
            buildingtype.price.resourceThree = buildingtype.price.resourceThree - discount
        else:
            buildingtype.price.resourceThree = 0
        if (buildingtype.price.resourceFour > discount):
            buildingtype.price.resourceFour = buildingtype.price.resourceFour - discount
        else:
            buildingtype.price.resourceFour = 0
        #check to see if they can afford the building they are buying
        if (buildingtype.price.resourceOne > colony.resourceStorage.resourceOne or
            buildingtype.price.resourceTwo > colony.resourceStorage.resourceTwo or
            buildingtype.price.resourceThree > colony.resourceStorage.resourceThree or
            buildingtype.price.resourceFour > colony.resourceStorage.resourceFour):
            self.redirect('/planet/view/')
            return

        #check to see if they have enough population to build the building
        if (planet.current_population + buildingtype.population < 0):
            self.redirect('/planet/view/')
            return    
        
        #they can afford the building, so now take the materials out of their colony
        #also if they are building a housing unit increases the max planet pop
        #if (buildingname == 'Small Housing Unit'):
        #    planet.native_population_capacity += 1
        #elif (buildingname == 'Medium Housing Unit'):
        #    planet.native_population_capacity += 4
        #elif (buildingname == 'Large Housing Unit'):
        #    planet.native_population_capacity += 7
        colony.resourceStorage.resourceOne -= buildingtype.price.resourceOne
        colony.resourceStorage.resourceTwo -= buildingtype.price.resourceTwo
        colony.resourceStorage.resourceThree -= buildingtype.price.resourceThree
        colony.resourceStorage.resourceFour -= buildingtype.price.resourceFour
        colony.resourceStorage.put()
        planet.current_population += buildingtype.population
        planet.pollution += 1
        bu = BuildingUnit(owner = account, planet = planet, type = buildingtype)
        #log action
        new_log = Log.log(account.email, "Bought a " + str(buildingname), planet.name, 
                              "Resources after buying a building: " + str(colony.resourceStorage.resourceOne) + 
                              "Water: " + str(colony.resourceStorage.resourceTwo) +
                              "Fuels: " + str(colony.resourceStorage.resourceThree) +
                              "Organic: " + str(colony.resourceStorage.resourceFour))
        #end of log action
        bu.put()
        account.put()
        planet.put()
        self.redirect('/planet/view/')

# Allow a player to purchase units
class PurchasePage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        account = get_account_from_user(user)
        # Require an account
        if account == None:
          self.redirect('/')
          return

        planet = account.current_planet

        colony = None
        for colony_key in planet.colonies:
            colony = Colony.get(colony_key)
            if colony.owner.key() == account.key():
                colonized = True
                break
        
        
        error_msg = []
        
        shipname = self.request.get('shippicked')
        #check to see if they selected a ship to buy
        if (not shipname):
            self.redirect('/planet/view/')
            return
        types = UnitType.all()
        shipstype = types.filter('type =',shipname)
        shipstype = shipstype[0]
        stored = colony.resourceStorage
        buyit = True
        #check to see if the discount buildings are already made
        buildingsUnits = BuildingUnit.all()
        userbuildings = buildingsUnits.filter('owner =', account).filter('planet =', planet)
        nano = 0
        auto = 0
        for building in userbuildings:
            if (building.type.name == 'Automated Production Lines'):
                auto = 2
            elif (building.type.name == 'Nanorobotics Assembly'):
                nano = 4
        discount = nano + auto
        #discount the price for the rest of this function
        if (shipstype.price.resourceOne > discount):
            shipstype.price.resourceOne = shipstype.price.resourceOne - discount
        else:
            shipstype.price.resourceOne = 0
        if (shipstype.price.resourceTwo > discount):
            shipstype.price.resourceTwo = shipstype.price.resourceTwo - discount
        else:
            shipstype.price.resourceTwo = 0
        if (shipstype.price.resourceThree > discount):
            shipstype.price.resourceThree = shipstype.price.resourceThree - discount
        else:
            shipstype.price.resourceThree = 0
        if (shipstype.price.resourceFour > discount):
            shipstype.price.resourceFour = shipstype.price.resourceFour - discount
        else:
            shipstype.price.resourceFour = 0
        #check to see if they can afford the ship they are buying
        if (shipstype.price.resourceOne > stored.resourceOne or
            shipstype.price.resourceTwo > stored.resourceTwo or
            shipstype.price.resourceThree > stored.resourceThree or
            shipstype.price.resourceFour > stored.resourceFour):
            buyit = False

        #check to see if they have enough population to build the ship
        if (planet.current_population + shipstype.population < 0):
            buyit = False
        
        if (buyit):
            #they can afford the ship so now take the materials out of their colony
            stored.resourceOne -= shipstype.price.resourceOne
            stored.resourceTwo -= shipstype.price.resourceTwo
            stored.resourceThree -= shipstype.price.resourceThree
            stored.resourceFour -= shipstype.price.resourceFour
            #added/create the correct ship to the account
            if (shipname == 'ColonyS'):
                cs = ColonyShip(owner = account, planet = planet, type = shipstype)
                cs.put()
                cs.name = "ColonyShip #"+str(cs.key().id())
                cs.put()
            elif (shipname == 'RecyclingS'):
                rs = RecyclingShip(owner = account, planet = planet, type = shipstype)
                rs.put()
                rs.name = "RecyclingShip #"+str(rs.key().id())
                rs.put()
            elif (shipname == 'FreighterS'):
                store = ResourcePackage(resourceOne=0, resourceTwo=0, resourceThree=0, resourceFour=0)
                store.put()
                fs = FreighterShip(owner = account, planet = planet, type = shipstype, storage = store)
                fs.put()
                fs.name = "FreighterShip #"+str(fs.key().id())
                fs.put()
            elif (shipname == 'MegaFreighterS'):
                store = ResourcePackage(resourceOne=0, resourceTwo=0, resourceThree=0, resourceFour=0)
                store.put()
                mfs = MegaFreighterShip(owner = account, planet = planet, type = shipstype, storage = store)
                mfs.put()
                mfs.name = "MegaFreighterShip #"+str(fs.key().id())
                mfs.put()
            elif (shipname == 'MOPPS'):
                mopps = MOPPShip(owner = account, planet = planet, type = shipstype)
                mopps.put()
                mopps.name = "RecyclingShip #"+str(rs.key().id())
                mopps.put()
            planet.pollution += 1
            planet.current_population += shipstype.population
            #log action
            new_log = Log.log(account.email, "Bought a " + str(shipname), planet.name, 
                              "Resources after buying a building: " + str(colony.resourceStorage.resourceOne) + 
                              "Water: " + str(colony.resourceStorage.resourceTwo) +
                              "Fuels: " + str(colony.resourceStorage.resourceThree) +
                              "Organic: " + str(colony.resourceStorage.resourceFour))
            #end of log action
            planet.put()
            stored.put()
            account.put()

        self.redirect('/planet/view/')


application = webapp.WSGIApplication(
                                     [('/planet/view/', ViewPage),
                                      ('/planet/clean/', CleanPlanet),
                                      ('/planet/purchase/', PurchasePage),
                                      ('/planet/marketplace', Marketplace),
                                      ('/planet/purchase/building/', PurchaseBuilding),
                                      ('/planet/storage/', ResourceStoring),
                                     ('/planet/colonize/', Colonize),],
                                     debug=True)									 
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
